/**
 * 
 */
package org.pump.client.codec;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import org.apache.mina.core.buffer.IoBuffer;
import org.pump.client.main.MyProperty;
import org.pump.client.type.LengthCodedString;
import org.pump.client.type.NullTerminatedString;
import org.pump.client.util.TypeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liudong03
 * 
 */
public class AuthPack extends PacketBody {
	private static final Logger mylog = LoggerFactory.getLogger(AuthPack.class);
	byte[] client_flags = { (byte) 0x85, (byte) 0xa6, 0x03, 0x00 };
	int max_packet_size;
	byte charset_number;
	byte[] filler1 = new byte[23];
	NullTerminatedString username;
	LengthCodedString scramble;
	NullTerminatedString databasename;
	
	public AuthPack(MyProperty conf, String randoms_seed)
	{
		this(conf.username,conf.password,randoms_seed,null,conf.charset,conf.maxPacketSize);
	}
	public AuthPack(String username, String password, String randoms_seed,
			String dbname, String charset,int max_packet_size) {
		this.username = new NullTerminatedString(username, "US-ASCII");
		this.len = 53 + this.username.len;
		byte[] scramble = null;
		try {
			scramble = EncodePassword.scramble411(password, randoms_seed,
					charset);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			mylog.error("ecnode password fail", e);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			mylog.error("ecnode password fail", e);
		}
		this.scramble = new LengthCodedString(scramble);
		this.max_packet_size = max_packet_size;

		if (dbname != null && dbname.length() != 0) {
			this.client_flags[0] = (byte) (this.client_flags[0] | 0x08);
			this.databasename = new NullTerminatedString(dbname, "US-ASCII");
			this.len = this.len + this.databasename.len;
		}
		
		this.charset_number = Integer.valueOf(TypeUtil.getCharsetID(charset)).byteValue();
	}

	public boolean writebuffer(IoBuffer out) {
		out.put(client_flags);
		out.putUnsignedInt(this.max_packet_size);
		out.put(charset_number);
		out.put(filler1);
		this.username.writeBuffer(out);
		this.scramble.writeBuffer(out);
		if (this.databasename != null) {
			this.databasename.writeBuffer(out);
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "AuthPack [client_flags=" + Arrays.toString(client_flags)
				+ ", max_packet_size=" + max_packet_size + ", charset_number="
				+ charset_number + ", filler1=" + Arrays.toString(filler1)
				+ ", username=" + username + ", scramble=" + scramble
				+ ", databasename=" + databasename + "]";
	}

}
